<template>
    <div id="register-result">
        
        <el-dialog
            title="登记巡检结果"
            v-model="resultDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
        >
            <template v-if="isLoading">
                <div style="text-align: center;height: 20vh;" v-loading="isLoading" element-loading-text="数据加载中..."></div>
            </template>
            <template v-else>
                <el-tabs
                    v-model="editableTabsValue"
                    type="card"
                    :addable="true"
                    class="demo-tabs"
                    @edit="handleTabsEdit"
                >
                    <el-tab-pane
                        v-for="item in editableTabs"
                        :key="item.name"
                        :closable="item.closable"
                        :name="item.name"
                    >
                        <template #label>
                            <el-tooltip
                                effect="dark"
                                :content="item.title"
                                placement="top"
                                popper-class="box-item"
                            >
                                <span :class="setClass" style="text-align: center;display: inline-table;width: 100px;" @click="handleSpan(item.content)">{{ formatLabel(item.title) }}</span>
                            </el-tooltip>
                        </template>
                    </el-tab-pane>
                </el-tabs>
                <div style="height: 20vh;" v-if="isConLoading" v-loading="isConLoading" element-loading-text="数据加载中..."></div>
                <div v-else>
                    <AddEditRegisterResult
                        ref="bas"
                        :getInfo="getInfo"
                        :componentKey="componentKey"
                        :treeData="treeData"
                        :typeData="typeData"
                        :echoInfo="echoInfo"
                        @handelUploadFile="handelUploadFile"
                    ></AddEditRegisterResult>
                </div>
            </template>
            
            <template #footer>
                <el-button v-if="isShowFinish" type="warning"  :loading="setDis" :disabled="setDis" @click="taskFinish">巡检任务完成</el-button>
                <el-button @click="cancelUseClick">关 闭</el-button>
                <el-button v-if="isShowResult" type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm">提交</el-button>
                <span v-else style="color: #F56C6C;margin-left: 20px;">巡检点登记已完成</span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch , nextTick } from 'vue';
import { TabPaneName , ElButton, ElDialog } from 'element-plus';
import { 
    SMSIPTaskContentList, 
    SMSHDHiddenAdd, 
    SMSHDHiddenList, 
    SMSHDRectifyList, 
    sysDictDataList, 
    SMSHDHiddenUpdate,
    SMSIPTaskComplete, 
} from '/@/api/centerControl/sms';
import { sysFileInfoYitId , sysOrgTree , sysFileInfoMultipleUpload } from '/@/api/centerControl/pubilc';
import AddEditRegisterResult from './add-edit-register-result.vue';

/*** 定义接口基础数据类型 */
interface formType {
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {}
export default defineComponent( {
    name: 'register-result',
    components: {AddEditRegisterResult},
    props: {
        resultDialog:{
            type: Boolean,
            default: false,
        },
        resultInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const isShowResult = ref(true);
        const editableTabsValue = ref('0');
        let tabIndex = 0;
        const editableTabs:any = ref([]);
        let needId = 0; // 巡检点id
        const isDialog = ref(false);
        const modelInfo = ref();
        const componentKey = ref(0);
        const treeData = ref('');
        const fileData = ref();
        const bas = ref(null);
        const echoInfo = ref();
        const typeData = ref();
        let abarId = 0; // 整改id（编辑的时候使用）
        let fileId = 0; // 文件id
        const isLoading = ref(true);
        const isConLoading = ref(true);
        const getInfo = reactive({
            keyId: 0,
            sourceId: 0,
            isControlled: null,
        });
        let isAddEdit = '';
        let isCustom = false;
        const setClass = ref();
        const isShowFinish = ref(false);
        const setDis = ref(false);
        const repeatDis = ref(false);

        // 生成随机数
        const generateUniqueRandomNumber = (min: number, max: number) => {
            const numbers = new Set();
            let randomNumber;
            do {
                randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
            } while (numbers.has(randomNumber));
            return randomNumber;
        }

        const formatLabel = (label: string) => {
            // 如果标签页标题长度超过指定长度，则进行省略处理
            const maxLength = 10; // 设置最大长度
            if (label.length > maxLength) {
                return label.slice(0, maxLength) + '...';
            }
            return label;
        };

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        };

        /*** 获取其它隐患登记数据 */
        const setTagFun = async() => {
            let getData: any = [];
            let res: any = await SMSHDHiddenList({l_IPTaskId: JSON.parse(props.resultInfo).id, isCustom: true});
            if(res.success && res.data.length !== 0){
                getData = res.data;
                getData.map((i: any) => {
                    i.l_SMSDCListId = i.id;
                    i.smsdcList = {v_CheckContent: '其它隐患登记'};
                });
            }
            return getData;
        }

        const setFun = async(targetName: TabPaneName | undefined, action: 'remove' | 'add') => {
            if (action === 'add') {
                const newTabName = `${++tabIndex}`
                editableTabs.value.push({
                    title: '其它隐患登记',
                    name: newTabName,
                    closable: true,
                    content: {l_SMSDCListId: 0, keyId: 0 , isCustom: false},
                });
                needId = 0;
                getInfo.keyId = 0;
                editableTabsValue.value = newTabName;
                isCustom = false;
            } else if (action === 'remove') {
                const tabs = editableTabs.value;
                let activeName = editableTabsValue.value;
                if (activeName === targetName) {
                    tabs.forEach((tab: any, index: any) => {
                        if (tab.name === targetName) {
                            const nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.name;
                            }
                        }
                    });
                }
                editableTabsValue.value = activeName;
                editableTabs.value = tabs.filter((tab: any) => tab.name !== targetName);
                if(editableTabs.value.length !== 0){
                    let len = editableTabs.value.length - 1;
                    needId = editableTabs.value[len].content.l_SMSDCListId;
                    getInfo.keyId = editableTabs.value[len].content.keyId;
                    isCustom = editableTabs.value[len].content.isCustom;
                }
            }
        }
        const handleTabsEdit = async(targetName: TabPaneName | undefined, action: 'remove' | 'add') => {
            isConLoading.value = true;
            await setFun(targetName,action);
            isShowResult.value = true;
            echoFun();
        };

        /*** 获取数据字典值 */
        const getDictFun = async() => {
            let setObj: any = {};
            let res: any;
            let ras: any;
            
            for(let i = 0; i < 2; i++){
                if(i === 0){
                    res = await sysDictDataList({ TypeCode: 'rectifyType' });
                }else{
                    ras = await sysDictDataList({ TypeCode: 'HiddenDangerType' });
                }
            }
            if(res.success && ras.success){
                setObj.typeOne = res.data;
                setObj.typeTwo = ras.data;
                typeData.value = JSON.stringify(setObj);
            }
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            isConLoading.value = false;
            isLoading.value = false;
            ctx.emit('cancelResultClick')
        };

        /*** 获取组织架构树 */
        const getTree = async() => {
            let param = {}
            let res: any = await sysOrgTree(param);
            if(res.success) treeData.value = JSON.stringify(res.data);
        }

        /*** 获取文件数据 */
        const handelUploadFile = (fileVal: any) => {
            fileData.value = fileVal;
        }

        /*** submitForm 提交事件 */
        const submitForm = () => {
            const getRef: any = bas.value;
            const isFormValid = getRef.ruleFormRef.validate();
            submitFun(isFormValid , getRef.ruleForm);
            // ctx.emit('controlResultClick')
        };
        /*** 提交函数 */
        const submitFun = (f: Function | any , i: any ) => {
            let subFun = f;
            subFun.then(async(result: any) => {
                if(result){
                    repeatDis.value = true;
                    i.l_SMSDCListId = needId === 0 ? null : needId;
                    i.l_IPTaskId = JSON.parse(props.resultInfo).id;
                    let setObj: object | any = {};
                    setObj.d_LimitTime = i.n_Types === 1 ? i.d_LimitTime : null;
                    setObj.l_RectifyUserId = i.l_RectifyUserId;
                    setObj.l_RectifyDeptId = i.l_RectifyDeptId;
                    setObj.v_Measures = i.v_Measures.join("，");
                    setObj.l_HDHiddenId = i.l_HDHiddenId;
                    setObj.n_Type = i.n_Types;
                    setObj.isSceneRectify = i.isSceneRectify;
                    let res: any;
                    try{
                        if(isAddEdit === 'add'){
                            i.rectifyAdd = setObj;
                            i.l_FileId = getInfo.sourceId;
                            res = await SMSHDHiddenAdd(i);
                        }else{
                            setObj.id = abarId;
                            i.rectifyUpdate = setObj;
                            res = await SMSHDHiddenUpdate(i);
                        }
                        if(res.success) uploadFile();
                        else repeatDis.value = false;
                    }catch(error){ repeatDis.value = false; }
                }
            }).catch((error: any) => {
                return false;
            });
        }
        
        const getInitFun = async() => {
            let res: any = await SMSIPTaskContentList({l_IPTaskId: JSON.parse(props.resultInfo).id});
            if(res.success) return res.data;
        }
        const asyncFun = async() => {
            if(fileData.value.fileVal.length !== 0){
                let setArr:any = [];
                fileData.value.fileVal.map((i: any) => {
                    setArr.push(i.raw);
                });
                let res: any;
                let param: any = {};
                param.files = setArr;
                param.sourceId = fileId;
                param.sourceType = 10;
                console.log(param,'param')
                res = await sysFileInfoMultipleUpload(param);
                if(res.success) return;
            }
        }
        /*** 文件上传 */
        const uploadFile = async() => {
            isConLoading.value = true;
            await asyncFun();
            if(getInfo.keyId === 0) await getFun();
            else echoFun();
            let getInit = await getInitFun();
            const foundVal = getInit.find((item: object | any) => item.isControlled === null);
            if(foundVal) isShowFinish.value = false;
            else isShowFinish.value = true;
            isShowResult.value = false;
        }

        // getDotFun 获取巡检点信息
        const getDotFun = async() => {
            let res: any;
            res = await SMSIPTaskContentList({l_IPTaskId: JSON.parse(props.resultInfo).id});
            console.log(res.data,'data')
            if(res.success && res.data.length !== 0) {
                res.data.map((i: any) => {
                    i.isCustom = false;
                });
                let setArr: any = [];
                let resArr = res.data;
                const getTag = setTagFun();
                let mergeArr: any = [];
                await getTag.then((res: any) => {
                    if(res.length === 0) mergeArr = resArr;
                    else mergeArr = [...resArr, ...res];
                });
                mergeArr.map((i: any, x: number) => {
                    if(i.isControlled === undefined || i.isControlled === false || i.isControlled === true) setClass.value = 'is-success';
                    if(i.isControlled === null) setClass.value = 'is-warning';

                    let setObj: any = {};
                    setObj.title = i.smsdcList.v_CheckContent;
                    setObj.name = x.toString();
                    setObj.closable = false;
                    setObj.content = {l_SMSDCListId: i.l_SMSDCListId , keyId: i.id , isControlled: i.isControlled , isCustom: i.isCustom};
                    setArr.push(setObj);
                });
                console.log(mergeArr,'mergeArr')
                isCustom = mergeArr[0].isCustom;
                needId = mergeArr[0].l_SMSDCListId;
                getInfo.keyId = mergeArr[0].id;
                getInfo.isControlled = mergeArr[0].isControlled;
                tabIndex = mergeArr.length;
                editableTabs.value = setArr;
                return mergeArr;
            }
        }

        /*** 获取风险点 */
        const getFun = async() => {
            let titleVal = await getDotFun();
            setTimeout(() => {
                const foundVal = titleVal.find((item: object | any) => item.isControlled === null);
                if(foundVal) isShowFinish.value = false;
                else isShowFinish.value = true;
                echoFun();
            },0)
            
        };

        /*** 监听resultDialog的变化 */
        watch(() => props.resultDialog,async(newVal) => {
            if(newVal){
                editableTabsValue.value = '0';
                tabIndex = 0;
                editableTabs.value = [];
                isShowResult.value = true;
                needId = 0;
                isCustom = false;
                isLoading.value = true;
                isShowFinish.value= false;
                setDis.value = false;
                repeatDis.value = false;
                await getFun();
                await getTree();
                await getDictFun();
            }
        });
        /** 获取雪花id */
        const getXhFun = async() => {
            let res: any;
            res = await sysFileInfoYitId({});
            if(res.success) {
                getInfo.sourceId = res.data;
                fileId = res.data;
            }
        }
        onMounted(() => {
            nextTick(() => {});
        });


        /*** 风险点击事件 */
        const handleSpan = (val: any) => {
            isConLoading.value = true;
            isCustom = val.isCustom;
            isShowResult.value = true;
            needId = val.l_SMSDCListId;
            getInfo.keyId = val.keyId;
            getInfo.isControlled = val.isControlled;
            echoFun();
        };

        /*** resultDialog 响应弹窗的关闭  */
        const resultDialog = computed(() => {
            return props.resultDialog
        });
        
        // 获取数据
        const getDataFun = async() => {
            let res: any;
            if(isCustom) res = await SMSHDHiddenList({l_IPTaskId: JSON.parse(props.resultInfo).id, id: needId});
            else res = await SMSHDHiddenList({l_IPTaskId: JSON.parse(props.resultInfo).id, l_SMSDCListId: needId});
            if(res.success && res.data.length !== 0){
                isAddEdit = 'edit';
                let resData = res.data[0];
                let param: any = {};
                param.l_HDHiddenId = resData.id;
                param.n_Times = 1;
                param.onlyMyRecord = false;
                fileId = resData.l_FileId;
                let rfs: any = await SMSHDRectifyList(param);
                if(rfs.success && rfs.data.length !== 0){
                    let item = rfs.data[0];
                    abarId = item.id; // 整改id
                    let setObj: any = {};
                    setObj.d_LimitTime = item.d_LimitTime; // 整改期限
                    setObj.l_RectifyUserId = item.l_RectifyUserId; // 整改人员id
                    setObj.v_RectifyUserName = item.v_RectifyUserName; // 整改人员名称
                    setObj.l_RectifyDeptId = item.l_RectifyDeptId; // 整改部门id
                    setObj.v_RectifyDeptName = item.v_RectifyDeptName; // 整改部门名称
                    setObj.v_Measures = item.v_Measures.split('，'); // 整改措施集合
                    setObj.l_HDHiddenId = item.l_HDHiddenId; // 隐患记录Id
                    setObj.n_Types = item.n_Type; // 整改类型
                    setObj.isSceneRectify = item.isSceneRectify; // 是否现场整改
                    let getObj = {...resData,...setObj};
                    let creatObj: any = {};
                    creatObj.num = generateUniqueRandomNumber(1,100);
                    creatObj.info = JSON.stringify(getObj);
                    echoInfo.value = creatObj;
                }
            }else{
                await getXhFun();
                let creatObj: any = {};
                abarId = 0;
                creatObj.num = generateUniqueRandomNumber(1,100);
                creatObj.info = '';
                echoInfo.value = creatObj;
                isAddEdit = 'add';
            }
        }
        /*** 获取回显数据 */
        const echoFun = async() => {
            await getDataFun();
            componentKey.value = generateUniqueRandomNumber(1,100);
            isLoading.value = false;
            isConLoading.value = false;
        }

        /*** 巡检任务完成按钮 */
        const taskFinish = async() => {
            setDis.value = true;
            try{
                let res: any = await SMSIPTaskComplete({id: JSON.parse(props.resultInfo).id});
                if(res.success){
                    setDis.value = false;
                    ctx.emit('controlResultClick');
                    ctx.emit('updateData');
                }else{
                    setDis.value = false;
                    ctx.emit('controlResultClick');
                }
            }catch(error){setDis.value = false;}
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            resultDialog,
            editableTabsValue,
            handleTabsEdit,
            editableTabs,
            formatLabel,
            handleSpan,
            isDialog,
            modelInfo,
            getInfo,
            componentKey,
            treeData,
            handelUploadFile,
            bas,
            echoInfo,
            typeData,
            isShowResult,
            isLoading,
            isConLoading,
            taskFinish,
            setClass,
            isShowFinish,
            setDis,
            repeatDis,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-tabs__item){
    padding: 0;
}
:deep(.el-tabs__item:nth-of-type(2)){
    padding: 0!important;
}
.is-success{
    color: #67C23A;
}
.is-warning{
    color: #E6A23C;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>